<template>
	<div>
		<el-dialog v-model="centerDialogVisible" title="用户登录" class="loginbox" align-center width="350px" center>
			<template #header="{ close, titleId, titleClass }">
				<h4 :id="titleId" :class="titleClass">用户登录</h4>
			</template>
			<el-form class="input-pwd" :model="form" :rules="rules" ref="ruleForm" label-width="55px" autocomplete="new-password">
				<el-form-item prop="account" label="账号">
					<el-input v-model="form.account" placeholder="请输入账号" />
				</el-form-item>
				<el-form-item prop="password" label="密码">
					<el-input v-model="form.password" placeholder="请输入密码" show-password />
				</el-form-item>
			</el-form>

			<!-- <el-button @click="register">注册</el-button> -->

			<template #footer>
				<div class="columnLayout minaxgap">
					<div class="Horizontalspacing"><span class="minfont center">没有账号？</span><el-button link type="primary" @click="register">立即注册</el-button></div>
					<el-button type="primary" @click="login()">登录</el-button>
					<!-- 图标 -->
					<div class="left Horizontalspacing minaxgap">
						<span class="minfont center minfont">三方账号登录:</span>
						<div class="Horizontalspacing minaxgap">
							<img class="loginnnk" src="../assets/img/mk.svg" alt="" @click="getWalletSignature()" />
							<div style="font-size: 20px" class="iconfont icon-GitHub" @click="loginWithGitHub"></div>
						</div>
					</div>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script>
	import { ethers } from 'ethers'
	import { mapState } from 'vuex'
	import { dataRequest as api, automaticLogin, Logoutoflogin } from '@/api/api'
	import sha256 from 'crypto-js/sha256'
	export default {
		name: 'name',
		computed: {
			...mapState(['logon', 'user']),
		},
		components: {
			// 组件
		},
		data() {
			return {
				// 账号密码
				account: '',
				password: '',
				centerDialogVisible: false,
				form: {
					account: '',
					password: '',
				},
				rules: {
					account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
					password: [{ required: true, message: '请输入密码', trigger: 'change' }],
				},
			}
		},
		methods: {
			register() {
				this.$router.push('/register')
				this.centerDialogVisible = false
			},
			center() {
				this.$router.push('/user')
			},
			//登陆成功获取JWT  然后 在这里存入数据  然后去请求登陆接口即可
			async login() {
				this.$refs['ruleForm'].validate(async valid => {
					if (valid) {
						let arr = await api(['JWT', { username: this.form.account, password: sha256(sha256(this.form.password)).toString() }])

						this.trueloing(arr)
					} else {
						return false
					}
				})

				// 每次都去尝试登陆
			},
			async trueloing(arr) {
				if (arr.code == 200) {
					const data = { id: 1, JWT: arr.data, userid: arr.massage, logon: false }
					if (await this.$indexedDB.getObject(data.id)) {
						// 存在修改
						this.$indexedDB.updateObject(data)
					} else {
						// 不存在 添加
						this.$indexedDB.addObject(data)
					}
					await automaticLogin()
					this.$message.success('登陆成功')
					this.centerDialogVisible = false
					this.$emit('custom-event')
				} else {
					this.$message.error('账号不存在或密码错误')
				}
			},
			async connectWallet() {
				if (window.ethereum) {
					try {
						await window.ethereum.request({ method: 'eth_requestAccounts' })
						const provider = new ethers.BrowserProvider(window.ethereum)
						// console.log(await provider.getSigner())
						return provider
					} catch (error) {
						this.$message.error('链接钱包失败')
					}
				} else {
					this.$message.error('请安装 MetaMask 或其他支持的钱包')
				}
			},
			// 获取钱包签名
			async getWalletSignature() {
				const walletProvider = await this.connectWallet()
				if (walletProvider) {
					// 这个通过后端获取
					const message = '登陆DEXC开发者社区' // 替换为您要签名的消息
					try {
						const signer = await walletProvider.getSigner()

						const signature = await signer.signMessage(message)
						console.log(signature)
						// 把签名结果发送到后端
						const recoveredAddress = ethers.verifyMessage(message, signature)
						// 提交到后台
						let arr = await api(['JWT', { address: recoveredAddress, message: message, signature: signature }])
						this.trueloing(arr)
						// 认证通过  那么
						console.log(arr)
						// 解签
						// 发送到后台解签
						// 流程 登录  后端生成一个密码    然后前端使用后端的密码签名   然后发送给登录  后端解密
						console.log('Recovered address:', recoveredAddress)
						return signature
					} catch (error) {
						this.$message.error('签名失败')
					}
				}
			},
			// gitub
			loginWithGitHub() {
				const currentPath = this.$route.path
				const client_id = '0282aacf69050a9690fb'
				const redirect_uri = `http://localhost:8080/login?path=${currentPath}`
				const scope = 'user' // 请求的权限范围
				const oauthUrl = `https://github.com/login/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`
				// 重定向至 GitHub OAuth 授权页面
				window.location.href = oauthUrl
			},
		},
		mounted() {
			this.form.account = ''
			this.form.password = ''
			if (!this.logon) {
				this.centerDialogVisible = true
			}
		},
	}
</script>
<style>
	.loginbox .el-dialog__body {
		padding-bottom: 0px !important;
	}
	.loginbox .el-dialog__footer {
		padding-top: 0 !important;
	}
</style>
<style scoped>
	.loginnnk {
		width: 20px;
		height: 20px;
	}
	.Roundheadportrait .image-slot {
		font-size: 20px;
	}
</style>
